
<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8" />
        <title>贪吃蛇小游戏源码 | Jiaozi の 小窝</title>
        <meta name="author" content="Jiaozi" />
        <meta name="description" content="欢迎光临" />
        <meta name="keywords" content="" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
        <link rel="icon" href="/images/favicon.png" />
        <script src="https://cdn.staticfile.org/vue/3.2.47/vue.global.prod.min.js"></script>
<link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/6.3.0/css/all.min.css" />
<link rel="stylesheet" href="/css/fonts.min.css" />
<script> const mixins = {}; </script>

<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>


<script src="https://cdn.staticfile.org/highlight.js/11.7.0/highlight.min.js"></script>
<link
    rel="stylesheet"
    href="https://cdn.staticfile.org/highlight.js/11.7.0/styles/github.min.css"
/>
<script src="/js/lib/highlight.js"></script>



<script src="/js/lib/preview.js"></script>









<link rel="stylesheet" href="/css/main.css" />

    <meta name="generator" content="Hexo 6.3.0"></head>
    <body>
        
        
<canvas
    id="fireworks"
    style="position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; pointer-events: none; z-index: 32767"
></canvas>
<script src="https://cdn.staticfile.org/animejs/3.2.1/anime.min.js"></script>
<script src="/js/fireworks.min.js"></script>

<canvas
    id="background"
    style="position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; pointer-events: none; z-index: -1"
></canvas>
<script src="/js/background.min.js"></script>

<div id="cursor"></div>
<link rel="stylesheet" href="/css/cursor.min.css" />
<script src="/js/cursor.min.js"></script>

        <div id="layout">
            <transition name="fade">
                <div id="loading" v-show="loading">
                    <div id="loading-circle">
                        <h2>LOADING</h2>
                        <p>加载过慢请开启缓存 浏览器默认开启</p>
                        
                        <img src="/images/loading.gif" />
                    </div>
                </div>
            </transition>
            <nav id="menu" :class="{ hidden: hiddenMenu, 'menu-color': menuColor}">
    <div id="desktop-menu">
        <a class="title" href="/">
            <span>JIAOZI の 小窝</span>
        </a>
        
        <a href="/">
            <i class="fa-solid fa-house fa-fw"></i>
            <span>&ensp;Home</span>
        </a>
        
        <a href="/about">
            <i class="fa-solid fa-id-card fa-fw"></i>
            <span>&ensp;About</span>
        </a>
        
        <a href="/archives">
            <i class="fa-solid fa-box-archive fa-fw"></i>
            <span>&ensp;Archives</span>
        </a>
        
        <a href="/categories/Hello">
            <i class="fa-solid fa-bookmark fa-fw"></i>
            <span>&ensp;Categories</span>
        </a>
        
        <a href="/tags/all">
            <i class="fa-solid fa-tags fa-fw"></i>
            <span>&ensp;Tags</span>
        </a>
        
        <a href="/music">
            <i class="fa-solid fa-musics fa-fw"></i>
            <span>&ensp;❤Music</span>
        </a>
        
        <a href="/loves">
            <i class="fa-solid fa-loves fa-fw"></i>
            <span>&ensp;❤Loves</span>
        </a>
        
    </div>
    <div id="mobile-menu">
        <div class="title" @click="showMenuItems = !showMenuItems">
            <i class="fa-solid fa-bars fa-fw"></i>
            <span>&emsp;JIAOZI の 小窝</span>
        </div>
        <transition name="slide">
            <div class="items" v-show="showMenuItems">
                
                <a href="/">
                    <div class="item">
                        <div style="min-width: 20px; max-width: 50px; width: 10%">
                            <i class="fa-solid fa-house fa-fw"></i>
                        </div>
                        <div style="min-width: 100px; max-width: 150%; width: 20%">Home</div>
                    </div>
                </a>
                
                <a href="/about">
                    <div class="item">
                        <div style="min-width: 20px; max-width: 50px; width: 10%">
                            <i class="fa-solid fa-id-card fa-fw"></i>
                        </div>
                        <div style="min-width: 100px; max-width: 150%; width: 20%">About</div>
                    </div>
                </a>
                
                <a href="/archives">
                    <div class="item">
                        <div style="min-width: 20px; max-width: 50px; width: 10%">
                            <i class="fa-solid fa-box-archive fa-fw"></i>
                        </div>
                        <div style="min-width: 100px; max-width: 150%; width: 20%">Archives</div>
                    </div>
                </a>
                
                <a href="/categories/Hello">
                    <div class="item">
                        <div style="min-width: 20px; max-width: 50px; width: 10%">
                            <i class="fa-solid fa-bookmark fa-fw"></i>
                        </div>
                        <div style="min-width: 100px; max-width: 150%; width: 20%">Categories</div>
                    </div>
                </a>
                
                <a href="/tags/all">
                    <div class="item">
                        <div style="min-width: 20px; max-width: 50px; width: 10%">
                            <i class="fa-solid fa-tags fa-fw"></i>
                        </div>
                        <div style="min-width: 100px; max-width: 150%; width: 20%">Tags</div>
                    </div>
                </a>
                
                <a href="/music">
                    <div class="item">
                        <div style="min-width: 20px; max-width: 50px; width: 10%">
                            <i class="fa-solid fa-musics fa-fw"></i>
                        </div>
                        <div style="min-width: 100px; max-width: 150%; width: 20%">❤Music</div>
                    </div>
                </a>
                
                <a href="/loves">
                    <div class="item">
                        <div style="min-width: 20px; max-width: 50px; width: 10%">
                            <i class="fa-solid fa-loves fa-fw"></i>
                        </div>
                        <div style="min-width: 100px; max-width: 150%; width: 20%">❤Loves</div>
                    </div>
                </a>
                
            </div>
        </transition>
    </div>
</nav>
<transition name="fade">
    <div id="menu-curtain" @click="showMenuItems = !showMenuItems" v-show="showMenuItems"></div>
</transition>

            <transition name="into">
                <div id="main" v-show="!loading">
                    <div class="article">
    <div>
        <h1>贪吃蛇小游戏源码</h1>
    </div>
    <div class="info">
        <span class="date">
            <span class="icon">
                <i class="fa-solid fa-calendar fa-fw"></i>
            </span>
            2023/6/21
        </span>
        
        <span class="category">
            <a href="/categories/%E4%BB%A3%E7%A0%81/">
                <span class="icon">
                    <i class="fa-solid fa-bookmark fa-fw"></i>
                </span>
                代码
            </a>
        </span>
        
        
        <span class="tags">
            <span class="icon">
                <i class="fa-solid fa-tags fa-fw"></i>
            </span>
            
            <span class="tag">
                
                <a href="/tags/all/" style="color: #00bcd4">all</a>
            </span>
            
            <span class="tag">
                
                <a href="/tags/%E4%BB%A3%E7%A0%81/" style="color: #ff7d73">代码</a>
            </span>
            
            <span class="tag">
                
                <a href="/tags/C/" style="color: #00a596">C++</a>
            </span>
            
            <span class="tag">
                
                <a href="/tags/python/" style="color: #03a9f4">python</a>
            </span>
            
        </span>
        
    </div>
    
    <div class="content" v-pre>
        <p>贪吃蛇源码<p></p>
<span id="more"></span>

<pre><code class="C++">#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;Windows.h&gt;//windows编程头文件
#include &lt;time.h&gt;
#include &lt;conio.h&gt;//控制台输入输出头文件

#define SNAKESIZE 100//蛇的身体最大节数
#define MAPWIDTH 78//宽度
#define MAPHEIGHT 24//高度

#ifndef __cplusplus

typedef char bool;
#define false 0
#define true  1

#endif

//食物的坐标
struct &#123;
    int x;
    int y;
&#125;food;

//蛇的相关属性
struct &#123;
    int speed;//蛇移动的速度
    int len;//蛇的长度
    int x[SNAKESIZE];//组成蛇身的每一个小方块中x的坐标
    int y[SNAKESIZE];//组成蛇身的每一个小方块中y的坐标

&#125;snake;

//将光标移动到控制台的(x,y)坐标点处
void gotoxy(int x, int y)
&#123;
    COORD coord;
    coord.X = x;
    coord.Y = y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
&#125;



//绘制游戏边框
void drawMap();
//随机生成食物
void createFood();
//按键操作
void keyDown();
//蛇的状态
bool snakeStatus();
//从控制台移动光标
void gotoxy(int x, int y);

int key = 72;//表示蛇移动的方向，72为按下“↑”所代表的数字

//用来判断蛇是否吃掉了食物，这一步很重要，涉及到是否会有蛇身移动的效果以及蛇身增长的效果
int changeFlag = 0;

int sorce = 0;//记录玩家的得分

int i;
void drawMap()
&#123;
    //打印上下边框
    for (i = 0; i &lt;= MAPWIDTH; i += 2)//i+=2是因为横向占用的是两个位置
    &#123;
        //将光标移动依次到(i,0)处打印上边框
        gotoxy(i, 0);
        printf(&quot;■&quot;);
        //将光标移动依次到(i,MAPHEIGHT)处打印下边框
        gotoxy(i, MAPHEIGHT);
        printf(&quot;■&quot;);
    &#125;

    //打印左右边框
    for (i = 1; i &lt; MAPHEIGHT; i++)
    &#123;
        //将光标移动依次到(0,i)处打印左边框
        gotoxy(0, i);
        printf(&quot;■&quot;);
        //将光标移动依次到(MAPWIDTH, i)处打印左边框
        gotoxy(MAPWIDTH, i);
        printf(&quot;■&quot;);
    &#125;

    //随机生成初试食物
    while (1)
    &#123;
        srand((unsigned int)time(NULL));
        food.x = rand() % (MAPWIDTH - 4) + 2;
        food.y = rand() % (MAPHEIGHT - 2) + 1;
        //生成的食物横坐标的奇偶必须和初试时蛇头所在坐标的奇偶一致，因为一个字符占两个字节位置，若不一致
        //会导致吃食物的时候只吃到一半
        if (food.x % 2 == 0)
            break;
    &#125;
    //将光标移到食物的坐标处打印食物
    gotoxy(food.x, food.y);
    printf(&quot;￥&quot;);

    //初始化蛇的属性
    snake.len = 3;
    snake.speed = 200;

    //在屏幕中间生成蛇头
    snake.x[0] = MAPWIDTH / 2 + 1;//x坐标为偶数
    snake.y[0] = MAPHEIGHT / 2;
    //打印蛇头
    gotoxy(snake.x[0], snake.y[0]);
    printf(&quot;■&quot;);

    //生成初试的蛇身
    for (i = 1; i &lt; snake.len; i++)
    &#123;
        //蛇身的打印，纵坐标不变，横坐标为上一节蛇身的坐标值+2
        snake.x[i] = snake.x[i - 1] + 2;
        snake.y[i] = snake.y[i - 1];
        gotoxy(snake.x[i], snake.y[i]);
        printf(&quot;■&quot;);
    &#125;
    //打印完蛇身后将光标移到屏幕最上方，避免光标在蛇身处一直闪烁
    gotoxy(MAPWIDTH - 2, 0);
    return;
&#125;

void keyDown()
&#123;
    int pre_key = key;//记录前一个按键的方向
    if (_kbhit())//如果用户按下了键盘中的某个键
    &#123;
        fflush(stdin);//清空缓冲区的字符

        //getch()读取方向键的时候，会返回两次，第一次调用返回0或者224，第二次调用返回的才是实际值
        key = _getch();//第一次调用返回的不是实际值
        key = _getch();//第二次调用返回实际值
    &#125;

    /*
    *蛇移动时候先擦去蛇尾的一节
    *changeFlag为0表明此时没有吃到食物，因此每走一步就要擦除掉蛇尾，以此营造一个移动的效果
    *为1表明吃到了食物，就不需要擦除蛇尾，以此营造一个蛇身增长的效果
    */
    if (changeFlag == 0)
    &#123;
        gotoxy(snake.x[snake.len - 1], snake.y[snake.len - 1]);
        printf(&quot;  &quot;);//在蛇尾处输出空格即擦去蛇尾
    &#125;

    //将蛇的每一节依次向前移动一节（蛇头除外）
    for (i = snake.len - 1; i &gt; 0; i--)
    &#123;
        snake.x[i] = snake.x[i - 1];
        snake.y[i] = snake.y[i - 1];
    &#125;

    //蛇当前移动的方向不能和前一次的方向相反，比如蛇往左走的时候不能直接按右键往右走
    //如果当前移动方向和前一次方向相反的话，把当前移动的方向改为前一次的方向
    if (pre_key == 72 &amp;&amp; key == 80)
        key = 72;
    if (pre_key == 80 &amp;&amp; key == 72)
        key = 80;
    if (pre_key == 75 &amp;&amp; key == 77)
        key = 75;
    if (pre_key == 77 &amp;&amp; key == 75)
        key = 77;

    /**
    *控制台按键所代表的数字
    *“↑”：72
    *“↓”：80
    *“←”：75
    *“→”：77
    */

    //判断蛇头应该往哪个方向移动
    switch (key)
    &#123;
    case 75:
        snake.x[0] -= 2;//往左
        break;
    case 77:
        snake.x[0] += 2;//往右
        break;
    case 72:
        snake.y[0]--;//往上
        break;
    case 80:
        snake.y[0]++;//往下
        break;
    &#125;
    //打印出蛇头
    gotoxy(snake.x[0], snake.y[0]);
    printf(&quot;■&quot;);
    gotoxy(MAPWIDTH - 2, 0);
    //由于目前没有吃到食物，changFlag值为0
    changeFlag = 0;
    return;
&#125;

void createFood()
&#123;
    if (snake.x[0] == food.x &amp;&amp; snake.y[0] == food.y)//蛇头碰到食物
    &#123;
        //蛇头碰到食物即为要吃掉这个食物了，因此需要再次生成一个食物
        while (1)
        &#123;
            int flag = 1;
            srand((unsigned int)time(NULL));
            food.x = rand() % (MAPWIDTH - 4) + 2;
            food.y = rand() % (MAPHEIGHT - 2) + 1;

            //随机生成的食物不能在蛇的身体上
            for (i = 0; i &lt; snake.len; i++)
            &#123;
                if (snake.x[i] == food.x &amp;&amp; snake.y[i] == food.y)
                &#123;
                    flag = 0;
                    break;
                &#125;
            &#125;
            //随机生成的食物不能横坐标为奇数，也不能在蛇身，否则重新生成
            if (flag &amp;&amp; food.x % 2 == 0)
                break;
        &#125;

        //绘制食物
        gotoxy(food.x, food.y);
        printf(&quot;￥&quot;);

        snake.len++;//吃到食物，蛇身长度加1
        sorce += 10;//每个食物得10分
        snake.speed -= 5;//随着吃的食物越来越多，速度会越来越快
        changeFlag = 1;//很重要，因为吃到了食物，就不用再擦除蛇尾的那一节，以此来造成蛇身体增长的效果
    &#125;
    return;
&#125;

bool snakeStatus()
&#123;
    //蛇头碰到上下边界，游戏结束
    if (snake.y[0] == 0 || snake.y[0] == MAPHEIGHT)
        return false;
    //蛇头碰到左右边界，游戏结束
    if (snake.x[0] == 0 || snake.x[0] == MAPWIDTH)
        return false;
    //蛇头碰到蛇身，游戏结束
    for (i = 1; i &lt; snake.len; i++)
    &#123;
        if (snake.x[i] == snake.x[0] &amp;&amp; snake.y[i] == snake.y[0])
            return false;
    &#125;
    return true;
&#125;

int main()
&#123;
    drawMap();
    while (1)
    &#123;
        keyDown();
        if (!snakeStatus())
            break;
        createFood();
        Sleep(snake.speed);
    &#125;

    gotoxy(MAPWIDTH / 2, MAPHEIGHT / 2);
    printf(&quot;Game Over!\n&quot;);
    gotoxy(MAPWIDTH / 2, MAPHEIGHT / 2 + 1);
    printf(&quot;本次游戏得分为：%d\n&quot;, sorce);
    Sleep(5000);
    return 0;
&#125;
</code></pre>
<pre><code class="python">import pygame
import random
import sys
import time
from pygame.locals import * # 从pygame模块导入常用的函数和常量

# 定义颜色变量
black_colour = pygame.Color(0, 0, 0)
white_colour = pygame.Color(255, 255, 255)
red_colour = pygame.Color(255, 0, 0)
grey_colour = pygame.Color(150, 150, 150)


# 定义游戏结束函数
def GameOver(gamesurface):
# 设置提示字体的格式
GameOver_font = pygame.font.SysFont(&quot;MicrosoftYaHei&quot;, 16)

# 设置提示字体的颜色
GameOver_colour = GameOver_font.render(&#39;Game Over&#39;, True, grey_colour)

# 设置提示位置
GameOver_location = GameOver_colour.get_rect()
GameOver_location.midtop = (320, 10)
gamesurface.blit(GameOver_colour, GameOver_location)

# 提示运行信息
pygame.display.flip()

# 等待5秒
time.sleep(5)

# 退出游戏
pygame.quit()

# 退出程序
sys.exit()


# 定义主函数
def main():
# 初始化pygame
pygame.init()
pygame.time.Clock()
ftpsClock = pygame.time.Clock()

# 创建一个窗口
gamesurface = pygame.display.set_mode((640, 480))

# 设置窗口的标题
pygame.display.set_caption(&#39;贪吃蛇~&#39;)

# 初始化变量
# 初始化贪吃蛇的起始位置
snakeposition = [100, 100]

# 初始化贪吃蛇的长度
snakelength = [[100, 100], [80, 100], [60, 100]]

# 初始化目标方块的位置
square_purpose = [300, 300]

# 初始化一个数来判断目标方块是否存在
square_position = 1

# 初始化方向，用来使贪吃蛇移动
derection = &quot;right&quot;
change_derection = derection

# 进行游戏主循环
while True:
# 检测按键
for event in pygame.event.get():
if event.type == QUIT:
# 退出程序
pygame.quit()
sys.exit()

elif event.type == KEYDOWN:
# 判断按的键,用w,s,a,d来表示上下左右
if event.key == K_RIGHT or event.key == ord(&#39;d&#39;):
change_derection = &quot;right&quot;
if event.key == K_LEFT or event.key == ord(&#39;a&#39;):
change_derection = &quot;left&quot;
if event.key == K_UP or event.key == ord(&#39;w&#39;):
change_derection = &quot;up&quot;
if event.key == K_DOWN or event.key == ord(&#39;s&#39;):
change_derection = &quot;down&quot;
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))

# 判断移动的方向是否相反
if change_derection == &#39;left&#39; and not derection == &#39;right&#39;:
derection = change_derection
if change_derection == &#39;right&#39; and not derection == &#39;left&#39;:
derection = change_derection
if change_derection == &#39;up&#39; and not derection == &#39;down&#39;:
derection = change_derection
if change_derection == &#39;down&#39; and not derection == &#39;up&#39;:
derection = change_derection

# 根据方向，改变坐标
if derection == &#39;left&#39;:
snakeposition[0] -= 20
if derection == &#39;right&#39;:
snakeposition[0] += 20
if derection == &#39;up&#39;:
snakeposition[1] -= 20
if derection == &#39;down&#39;:
snakeposition[1] += 20

# 增加蛇的长度
snakelength.insert(0, list(snakeposition))

# 判断是否吃掉目标方块
if snakeposition[0] == square_purpose[0] and snakeposition[1] == square_purpose[1]:
square_position = 0
else:
snakelength.pop()

# 重新生成目标方块
if square_position == 0:
# 随机生成x,y,扩大二十倍，在窗口范围内
x = random.randrange(1, 32)
y = random.randrange(1, 24)
square_purpose = [int(x * 20), int(y * 20)]
square_position = 1
# 绘制pygame显示层
gamesurface.fill(black_colour)
for position in snakelength:
pygame.draw.rect(gamesurface, white_colour, Rect(position[0], position[1], 20, 20))
pygame.draw.rect(gamesurface, red_colour, Rect(square_purpose[0], square_purpose[1], 20, 20))

# 刷新pygame显示层
pygame.display.flip()

# 判断是否死亡
if snakeposition[0] &lt; 0 or snakeposition[0] &gt; 620:
GameOver(gamesurface)
if snakeposition[1] &lt; 0 or snakeposition[1] &gt; 460:
GameOver(gamesurface)
for snakebody in snakelength[1:]:
if snakeposition[0] == snakebody[0] and snakeposition[1] == snakebody[1]:
GameOver(gamesurface)

# 控制游戏速度
ftpsClock.tick(5)


if __name__ == &quot;__main__&quot;:
main()
</code></pre>

    </div>
    
    
    
    
    
    
    
</div>

                    <footer id="footer">
    <div id="footer-wrap">
        <div>
            
            &copy;
            2023 - 2023 Jiaozi の 小窝
            <span id="footer-icon">
                <i class="fa-solid fa-font-awesome fa-fw"></i>
            </span>
            &commat;Jiaozi
        </div>
        <div>
            Based on the <a target="_blank" rel="noopener" href="https://hexo.io">Hexo Engine</a> &amp;
            <a target="_blank" rel="noopener" href="https://jiaozi0925.cn/">Jiaozi</a>
        </div>
        
        <div>
            备案号：
            
            <a target="_blank" rel="noopener" href="https://icp.gov.moe/?keyword=20230599">萌ICP备20230599号</a>
            
        </div>
        
    </div>
    <!--添加网站运行时间 -->
<!--<br/>-->
<span id="timeDate">载入天数...</span><span id="times">载入时分秒...</span>
<script>
    var now = new Date();

    function createtime() {
        var grt = new Date("06/04/2023 12:00:00"); //此处修改你的建站时间或者网站上线时间 
        now.setTime(now.getTime() + 250);
        days = (now - grt) / 1000 / 60 / 60 / 24;
        dnum = Math.floor(days);
        hours = (now - grt) / 1000 / 60 / 60 - (24 * dnum);
        hnum = Math.floor(hours);
        if (String(hnum).length == 1) {
            hnum = "0" + hnum;
        }
        minutes = (now - grt) / 1000 / 60 - (24 * 60 * dnum) - (60 * hnum);
        mnum = Math.floor(minutes);
        if (String(mnum).length == 1) {
            mnum = "0" + mnum;
        }
        seconds = (now - grt) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
        snum = Math.round(seconds);
        if (String(snum).length == 1) {
            snum = "0" + snum;
        }
        document.getElementById("timeDate").innerHTML = " 本站已安全运行 " + dnum + " 天 ";
        document.getElementById("times").innerHTML = hnum + " 小时 " + mnum + " 分 " + snum + " 秒";
    }
    setInterval("createtime()", 250);
</script>
<!-- 添加网站运行时间 -->

</footer>




                </div>
            </transition>
            
            <transition name="fade">
                <div id="preview" ref="preview" v-show="previewShow">
                    <img id="preview-content" ref="previewContent" />
                </div>
            </transition>
            
        </div>
        <script src="/js/main.js"></script>
        
        




        
    </body>
</html>

